package uk.co.agileworks.bidpirate.service;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import uk.co.agileworks.bidpirate.model.Bid;
import uk.co.agileworks.bidpirate.model.Item;
import uk.co.agileworks.bidpirate.model.Status;
import uk.co.agileworks.bidpirate.model.User;
import uk.co.agileworks.bidpirate.web.UserSession;

// TODO @Transactional
@Service
public final class BusinessLogicImpl implements BusinessLogic {

	private static final Logger LOGGER = LoggerFactory.getLogger(BusinessLogicImpl.class);

	@Autowired
	private ApplicationContext ctx;

	@Autowired
	private DAO dao;

	@Autowired
	private EbayFacade ebayFacade;

	@Autowired
	private UserSession userSession;

	@Override
	public void addBid(Bid bid) {
		bid.setStatus(userSession.isLoggedIn() ? Status.ACTIVE : Status.PENDING);
		bid.checkStatus();
		dao.saveOrUpdateBid(bid);
	}

	@Override
	public void deleteBid(long id) {
		Bid bid = dao.getBid(id);
		dao.deleteBid(bid);
	}

	@Override
	public void editBid(Bid bid) {
		bid.checkStatus();
		dao.saveOrUpdateBid(bid);
	}

	@Override
	public Bid getBid(long id) {
		return dao.getBid(id);
	}

	@Override
	public List<Bid> listBids(User user) {
		List<Bid> bids = new ArrayList<Bid>();
		if (user.getId() != null) {
			bids = dao.getBids(user);
		}
		return bids;
	}

	@Override
	public boolean logIn(User userObj) {
		LOGGER.debug("userObj=" + userObj);
		EbaySession ebaySession = getEbaySession();
		boolean signedIn = ebaySession.signIn(userObj);
		if (signedIn) {
			User sessionUser = userSession.getUser();
			LOGGER.debug("sessionUser=" + sessionUser);
			User persistedUser = dao.getUser(userObj.getUsername());
			LOGGER.debug("persistedUser=" + persistedUser);
			if (persistedUser == null) {
				userObj.setId(sessionUser.getId());
				dao.saveOrUpdateUser(userObj);
				persistedUser = userObj;
			}
			if (sessionUser.getId() != null) {
				for (Bid bid : dao.getBids(sessionUser)) {
					bid.setStatus(Status.ACTIVE);
					bid.checkStatus();
					bid.setUser(persistedUser);
					dao.saveOrUpdateBid(bid);
				}
			}
			persistedUser.setRegion(userObj.getRegion());
			userSession.logIn(persistedUser);
			ebaySession.signOut();
		}
		return signedIn;
	}

	@Override
	public void updatePrice(long bidId) {
		Bid bid = dao.getBid(bidId);
		String itemUrl = ebayFacade.getItemUrl(bid.getItem().getItemNumber());
		Item item = ebayFacade.parseItem(itemUrl);
		bid.getItem().setPrice(item.getPrice());
		dao.saveOrUpdateBid(bid);
	}

	private EbaySession getEbaySession() {
		return ctx.getBean(EbaySession.class);
	}

}
